package nuffzone;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class recipeServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User user = userService.getCurrentUser();
		recipeManager RM = recipeManager.getInstance();
		categoriesManager CM = categoriesManager.getInstance();
		String request = req.getParameter("request");
		Map<String, Object> data = new HashMap<String, Object>();
		if (request.equals("getRecipesOfCategory")) {
			System.out.println("******GET RECIPES OF CATEGORY******");
			String category = req.getParameter("categoryName");
			System.out.println("=> "+category);
			ArrayList<Recipe> recipeList = RM.getAllUserRecipesOfCategory(user, category);
			data.put("recipeList", recipeList);
			System.out.println("-----------------------------------");
			System.out.println(" ");
		} else if (request.equals("getRecipe")) {
			System.out.println("******GET RECIPE*******************");
			String name = req.getParameter("name");
			if (name.length() != 0) {
				Recipe recipe = RM.getRecipe(user, name);
				data.put("name", recipe.getTitle());
				System.out.println("=> "+recipe.getTitle());
				data.put("ingredientList", recipe.getIngredientList());
				data.put("description",	recipe.getDescription().replaceAll("\n", "<br />"));
			}
			System.out.println("-----------------------------------");
			System.out.println(" ");
		} else if(request.equals("getAllRecipesOfUser")){
			System.out.println("******GET ALL RECIPES OF USER******");
			ArrayList<String> categoryList = CM.getCategoriesOfUser(user);
			System.out.println("=> "+user);
			for(String category:categoryList){
				ArrayList<Recipe> recipeList = RM.getAllUserRecipesOfCategory(user, category);
				data.put(category,recipeList);
			}
			System.out.println("-----------------------------------");
			System.out.println(" ");
		} else if(request.equals("getRecipeFromInputText")){
			System.out.println("******GET RECIPE THAT MATCHES INPUTTEXT******");
			String inputText = req.getParameter("inputText");
			Recipe recipe = RM.getRecipeThatMatchesInputText(inputText, user);
			if(recipe!=null){
				data.put("name", recipe.getTitle());
				System.out.println("=> "+recipe.getTitle());
				data.put("ingredientList", recipe.getIngredientList());
				data.put("description", recipe.getDescription().replaceAll("\n", "<br />"));
			}
			else{
				System.out.println("Failed to find a match for the given input text.");
			}
				System.out.println("-----------------------------------");
				System.out.println(" ");
		}
		
		// Write response data as JSON.
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().write(new Gson().toJson(data));
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User user = userService.getCurrentUser();
		recipeManager RM = recipeManager.getInstance();
		if (user == null) {
			System.out.println("user is null<<<<<<<");
		} else {
			String request = req.getParameter("request");
			if (request.equals("createRecipe")) {
				System.out.println("******CREATE RECIPE****************");
				String name = req.getParameter("name");
				System.out.println("name = "+name);
				if (name.length() != 0) {
					String category = req.getParameter("category");
					if (category != "null") {
						ArrayList<String> categories = new ArrayList<String>();
						categories.add(category);
						int nBofIngredients = Integer.parseInt(req
								.getParameter("nbOfIngredients"));
						ArrayList<Ingredient> ingredientList = new ArrayList<Ingredient>();
						for (int i = 1; i <= nBofIngredients; i++) {
							String ingredientname = req
									.getParameter("ingredient" + i + "name");
							String ingredientquantity = req
									.getParameter("ingredient" + i + "quantity");
							ingredientList.add(new Ingredient(ingredientname,
									ingredientquantity));
						}
						String description = req.getParameter("description");
						RM.createRecipe(name, ingredientList, null,
								description, categories, user);
					} else {
						resp.setStatus(402);// NO CATEGORY SELECTED
					}
				} else {
					resp.setStatus(401);// NO NAME FILLED IN
				}
			System.out.println("-----------------------------------");
			System.out.println(" ");
			} else if (request.equals("deleteRecipe")) {
				System.out.println("******DELETE RECIPE****************");
				String recipeName = req.getParameter("recipeName");
				System.out.println("=> "+recipeName);
				RM.deleteRecipe(user, recipeName);
				System.out.println("-----------------------------------");
				System.out.println(" ");
			} else {
				resp.setStatus(403);// WRONG REQUEST
			}
		}
		resp.setStatus(200);
		resp.sendRedirect("/recipes.jsp");
	}
}